﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using HolcimProject.Function;
using HolcimProject.Common.DTO;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using HolcimProject.Common;
using System.Collections.Generic;
using System.Web;
using SPTraceLogger;

namespace HolcimProject.ControlTemplates.HolcimProject
{
    public partial class FindingUpdateEvidence : UserControl
    {
        string personInchargeUser = "";
        int findingID = 0;
        string state = "";

        #region Property
        public int FindingID
        {
            get
            {
                try
                {
                    return findingID;
                    //return Convert.ToInt32(Request.QueryString["findingid"]);
                    //return 10;
                }
                catch
                {
                    return 0;
                }
            }
        }

        public int FindingTaskID
        {
            get
            {
                try
                {
                    return Convert.ToInt32(Request.QueryString["findingtaskid"]);
                    //return 6;
                }
                catch
                {
                    return 0;
                }
            }
        }
        #endregion

        #region Event
        private FunctionFinding functionFinding;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                functionFinding = new FunctionFinding();
                // get parameter
                GetParameter();
                if (!Page.IsPostBack)
                {
                    // Load information process
                    LoadInformationProcess();
                    // Load information finding
                    LoadInfoFinding();

                    //check permission
                    CheckPermission();
                }
            }
            catch (Exception ex)
            {
                SPLoggingService.WriteULSError("Finding", Categories.WebPart, ex);
            }
        }

        protected void btnEditActionLogs_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidationAttachFile())
                {
                    // update comment for this task
                    FindingTaskDTO findingTaskComment = getInfoCommentLog();
                    findingTaskComment.Status = Constants.Status_NoYet;
                    functionFinding.UpdateCommentTask(findingTaskComment);
                    // Update evidence
                    functionFinding.UpdateEvidence(GetInfoEvidence());
                    // Create task for next step
                    FindingDTO findingLoad = functionFinding.GetFindingByID(FindingID, Constants.State_UpdateEvidence);
                    if (findingLoad != null)
                    {
                        FindingTaskDTO findingTask = new FindingTaskDTO();
                        findingTask = GetInfoTask(findingLoad.Auditee, Constants.Role_Auditee, Constants.State_EditActionLog, Constants.Status_NoYet);
                        functionFinding.UpdateTask(findingTask);
                    }
                    //close form
                    closeForm();
                }
            }
            catch (Exception ex)
            {
                messageError.InnerHtml = "This action cannot be performed successfully. Please contact your system administrator or try again.";
                SPLoggingService.WriteULSError("Finding", Categories.WebPart, ex);
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidationAttachFile())
                {
                    // update comment for this task
                    FindingTaskDTO findingTaskComment = getInfoCommentLog();
                    findingTaskComment.Status = Constants.Status_OnGoing;
                    functionFinding.UpdateCommentTask(findingTaskComment);
                    // Update evidence
                    functionFinding.UpdateEvidence(GetInfoEvidence());
                    // Create task for next step
                    FindingDTO findingLoad = functionFinding.GetFindingByID(FindingID, Constants.State_UpdateEvidence);
                    if (findingLoad != null)
                    {
                        FindingTaskDTO findingTask = new FindingTaskDTO();
                        findingTask = GetInfoTask(findingLoad.Auditor, Constants.Role_Auditor, Constants.State_ApproveEvidence_Auditor, Constants.Status_OnGoing);
                        functionFinding.UpdateTask(findingTask);
                    }
                    //close form
                    closeForm();
                }
            }
            catch (Exception ex)
            {
                messageError.InnerHtml = "This action cannot be performed successfully. Please contact your system administrator or try again.";
                SPLoggingService.WriteULSError("Finding", Categories.WebPart, ex);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            
            closeForm();
        }
        #endregion



        #region Function

        /// <summary>
        /// Get parameter
        /// </summary>
        private void GetParameter()
        {
            ParameterDTO parameter = functionFinding.GetParameterByFindTaskID(FindingTaskID);
            if (parameter != null)
            {
                state = parameter.State;
                findingID = parameter.FindingID;
            }
        }


        private FindingDTO GetInfoEvidence()
        {
            FindingDTO finding = new FindingDTO();
            finding.Id = FindingID;
            finding.Evidence = txtEvidence.Text;

            return finding;
        }

        /// <summary>
        /// Get info task
        /// </summary>
        /// <returns></returns>
        private FindingTaskDTO GetInfoTask(string owner, string role, string state, string status)
        {
            FindingTaskDTO findingTask = new FindingTaskDTO();
            findingTask.IdFinding = FindingID.ToString();
            findingTask.Owner = owner;
            findingTask.Role = role;
            findingTask.State = state;
            findingTask.Status = status;
            return findingTask;
        }

        /// <summary>
        /// Get comment update log
        /// </summary>
        /// <returns></returns>
        private FindingTaskDTO getInfoCommentLog()
        {
            FindingTaskDTO findingTask = new FindingTaskDTO();
            findingTask.Id = FindingTaskID;
            findingTask.Flat = "done";
            if (attackFile.FileName != "")
            {
                findingTask.AttackFileName = attackFile.FileName;
                findingTask.AttackFile = attackFile.FileBytes;
            }
            return findingTask;
        }

        /// <summary>
        /// Load info finding
        /// </summary>
        private void LoadInfoFinding()
        {
            FindingDTO findingLoad = new FindingDTO();
            findingLoad = functionFinding.GetFindingByID(FindingID, Constants.State_UpdateEvidence);
            string html = "";
            if (findingLoad != null)
            {
                // get person in charge user
                personInchargeUser = findingLoad.PersonInChage;

                html += "<table class='ms-formtable'>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Clause";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.Clause == "" ? "" : findingLoad.Clause.Split('#')[1];
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Site";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.Site == "" ? "" : findingLoad.Site.Split('#')[1]; ;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Department";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.Department == "" ? "" : findingLoad.Department.Split('#')[1]; ;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Auditee Department";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.AuditeeDepartment == "" ? "" : findingLoad.AuditeeDepartment.Split('#')[1]; ;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Item";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.System == "" ? "" : findingLoad.System.Split('#')[1]; ;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Classification";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.Classification == "" ? "" : findingLoad.Classification.Split('#')[1]; ;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Lead Auditor";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.LeadAuditor == "" ? "" : findingLoad.LeadAuditor.Split('\\')[1];
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Auditee";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.Auditee == "" ? "" : findingLoad.Auditee.Split('\\')[1];
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Finding(s)";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.Finding;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Correction";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.Correction;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Root Cause";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.RootCause;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Corrective/Preventive Action(s):";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.Corrective;
                html += "</td >";
                html += "<tr>";

                html += "<tr class=''>";
                html += "<td class='ms-formlabel'>Complete Date";
                html += "</td >";
                html += "<td class='ms-formbody'>";
                html += findingLoad.CompleteDate == null ? "" : findingLoad.CompleteDate.ToString("MM/dd/yyyy");
                html += "</td >";
                html += "<tr>";

                html += "</table>";

                txtEvidence.Text = findingLoad.Evidence;
            }
            InformationFinding.InnerHtml = html;
        }

        /// <summary>
        /// Load all tasks of finding
        /// </summary>
        private void LoadInformationProcess()
        {
            try
            {
                List<FindingTaskDTO> lst = new List<FindingTaskDTO>();
                lst = functionFinding.GetAllTaskOfFindingByID(FindingID);
                string html = "";
                if (lst != null)
                {
                    html += "<table class='tableInformationProcessing'>";
                    html += "<tr class='ms-viewheadertr ms-vhltr headerinformationprocess'>";

                    html += "<td class='ms-vh' style='width:3%'>";
                    html += "</td >";

                    html += "<td class='ms-vh' style='width:12%'>Date";
                    html += "</td >";

                    html += "<td class='ms-vh' style='width:12%'>Name";
                    html += "</td >";

                    html += "<td class='ms-vh' style='width:12%'>Role";
                    html += "</td >";

                    html += "<td class='ms-vh' style='width:12%'>State";
                    html += "</td >";

                    html += "<td class='ms-vh' style='width:12%'>Status";
                    html += "</td >";

                    html += "<td class='ms-vh' style='width:37%'>Comment";
                    html += "</td >";
                    html += "</tr>";
                    foreach (FindingTaskDTO findingTask in lst)
                    {
                        html += "<tr class='ms-alternating ms-itmhover rowInformationProcessing'>";

                        html += "<td class='ms-vb2' style='width:3%'>";
                        if (findingTask.AttackFileUrl != "")
                        {
                            html += "<a href='" + findingTask.AttackFileUrl + "'>";
                            html += "<img border='0' class='ms-vb-lvitemimg' title='Attachment' alt='Attachment' src='/_layouts/images/attach.gif'>";
                            html += "</a>";
                        }
                        html += "</td >";

                        html += "<td class='ms-vb2' style='width:12%'>";
                        html += "<div class='ms-rtestate-field'>";
                        html += findingTask.DateLastModify.ToString("MM/dd/yyyy");
                        html += "</div>";
                        html += "</td >";

                        html += "<td class='ms-vb2' style='width:12%'>";
                        html += "<div class='ms-rtestate-field'>";
                        try
                        {
                            html += findingTask.Owner == "" ? "" : findingTask.Owner.Split('\\')[1];
                        }
                        catch
                        {
                        }
                        html += "</div>";
                        html += "</td >";

                        html += "<td class='ms-vb2' style='width:12%'>";
                        html += "<div class='ms-rtestate-field'>";
                        html += findingTask.Role;
                        html += "</div>";
                        html += "</td >";

                        html += "<td class='ms-vb2' style='width:12%'>";
                        html += "<div class='ms-rtestate-field'>";
                        html += findingTask.State;
                        html += "</div>";
                        html += "</td >";

                        html += "<td class='ms-vb2'  style='width:12%'>";
                        html += "<div class='ms-rtestate-field'>";
                        html += findingTask.Status;
                        html += "</div>";
                        html += "</td >";

                        html += "<td class='ms-vb2' style='width:37%'>";
                        html += "<div class='ms-rtestate-field'>";
                        html += findingTask.Comment;
                        html += "</div>";
                        html += "</td >";
                        html += "</tr>";


                    }
                    html += "</table>";
                }
                InformationProcess.InnerHtml = html;
            }
            catch
            {
            }

        }

        /// <summary>
        /// close dialog Sharepoint
        /// </summary>
        private void closeForm()
        {
            HttpContext context = HttpContext.Current;
            if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
            {
                context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
                context.Response.Flush();
                context.Response.End();
            }
        }

        /// <summary>
        /// Check permission
        /// </summary>
        private void CheckPermission()
        {
            SPUser currentUser = Utilities.GetCurrentUser(Constants.Site_Url);
            if (personInchargeUser != "")
            {
                if (currentUser.LoginName.ToUpper() != personInchargeUser.Split('#')[1].ToUpper())
                {
                    ShowOrHideButton(false);
                }
            }
            else
            {
                ShowOrHideButton(false);
            }

        }

        /// <summary> 
        /// enable or disable button
        /// </summary>
        /// <param name="flat"></param>
        private void ShowOrHideButton(bool flat)
        {
            btnEditActionLogs.Enabled = flat;
            btnSend.Enabled = flat;
        }

        /// <summary>
        /// Validation select file
        /// </summary>
        /// <returns></returns>
        private bool ValidationAttachFile()
        {
            if (attackFile.FileName != "")
            {
                if (!CheckFileType(System.IO.Path.GetExtension(attackFile.FileName)))
                {
                    messageError.InnerHtml = "Not support this file type attach.";
                    return false;
                }
                if (attackFile.FileContent.Length > Constants.File_Attach_FileSize)
                {
                    messageError.InnerHtml = "Maximum size of uploaded file should be less than 50 MB.";
                    return false;
                }

                if (attackFile.FileContent.Length == 0)
                {
                    messageError.InnerHtml = "The file attach have not content. Please choose another file.";
                    return false;
                }
                messageError.InnerHtml = "";
                return true;
            }
            else
            {
                messageError.InnerHtml = "";
                return true;
            }
        }

        /// <summary>
        /// Check file type 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private bool CheckFileType(string type)
        {
            for (int i = 0; i < Constants.arrFileType.Length; i++)
            {
                if (Constants.arrFileType[i].ToLower() == type.ToLower())
                {
                    return false;
                }
            }
            return true;
        }

        #endregion
    }
}
